import { onMounted, Ref, watch } from 'vue'
import { createClassApplier } from '@notjosh/rangy-classapplier'
import { Highlighter, createHighlighter } from '@notjosh/rangy-highlighter'
import { useAnnotationStore } from '@/stores/annotation'
import { getSelection } from '@notjosh/rangy-core'
import { usePreferenceStore } from '@/stores/preference'

const annotationStore = useAnnotationStore()
const preferenceStore = usePreferenceStore()

function useHighlighter(frameRef: Ref<HTMLIFrameElement>) {
  let highlighter: Highlighter

  onMounted(() => {
    highlighter = createHighlighter(frameRef.value.contentDocument!)
    preferenceStore.colorList.forEach((c) => {
      highlighter.addClassApplier(
        createClassApplier(c.name, {
          elementAttributes: {
            style: 'background: ' + c.value + '; color: #333',
          },
        })
      )
    })
  })

  watch(
    () => preferenceStore.colorList,
    () => {
      clearHighlight()
      highlighter.classAppliers = {}
      preferenceStore.colorList.forEach((c) => {
        highlighter.addClassApplier(
          createClassApplier(c.name, {
            elementAttributes: {
              style: 'background: ' + c.value,
            },
          })
        )
      })
      highlightData()
    },
    { deep: true }
  )

  const highlightData = () => {
    clearHighlight()
    annotationStore.presentLabelList.forEach((label) => {
      if (!label.serializeError && label.bookmark) {
        getSelection(frameRef.value.contentWindow!).moveToBookmark(
          label.bookmark
        )
        highlighter.highlightSelection(
          preferenceStore.tagColor(label.tagId)?.colorName,
          { exclusive: false }
        )
        getSelection(frameRef.value.contentWindow!).removeAllRanges()
      }
    })
  }

  const clearHighlight = () => {
    highlighter.removeAllHighlights()
  }

  return {
    highlightData,
    clearHighlight,
  }
}

export { useHighlighter }
